package com.fs.m.server.function.test;

import com.fs.m.server.domain.RequestContext;
import com.fs.m.server.domain.Result;
import com.fs.m.server.domain.ResultCode;
import com.fs.m.server.function.Function;
import com.fs.m.server.util.MapUtil;

import java.util.*;

/**
 * 搜索接口
 *
 * User: zhuguoyin
 * Date: 13-10-8
 * Time: 下午10:48
 * To change this template use File | Settings | File Templates.
 */
public class SearchFunction1 implements Function {
    @Override
    public Result execute() throws Exception {
        Result validateResult = validateParameter();
        if (validateResult != null) {
            return validateResult;
        }
        Map param = RequestContext.get().getParam();
        MapUtil.getString(param, "keyword");
        List items = new ArrayList();
        int startIndex;
        int page;
        int pageSize;
        if (param == null || !param.containsKey("page")) {
            page = 1;
        } else {
            page = MapUtil.getInt(param, "page");
        }

        if (param == null || !param.containsKey("pageSize")) {
            pageSize = 10;
        } else {
            pageSize = MapUtil.getInt(param, "pageSize");
        }

        startIndex = (page - 1) * pageSize;

        for (int i = startIndex; i < startIndex + pageSize; i++) {
            Map item = new HashMap();
            item.put("id", i);
            item.put("name", "摩丝摩丝" + i);
            item.put("url", "http://www.baidu.com");
            item.put("downloadCount", new Random().nextInt(1000));
            items.add(item);
        }
        Result result = new Result();
        result.addResultData("items", items);
        return result;
    }

    private Result validateParameter() {
        Map param = RequestContext.get().getParam();
        if (param == null || param.isEmpty()) {
            Result r = new Result();
            r.addResultData("code", ResultCode.PARAMETER_ERROR.getCode());
            r.addResultData("message", "没有关键字");
            return r;
        }
        String key = MapUtil.getString(param, "keyword");
        if (key == null || key.length() == 0) {
            Result r = new Result();
            r.addResultData("code", ResultCode.PARAMETER_ERROR.getCode());
            r.addResultData("message", "没有关键字");
            return r;
        }
        return null;
    }
}
